<template>
	<view class="crop-container">
		<!-- 顶部操作栏 -->
		<view class="crop-header">
			<view class="header-btn" @tap="cancelCrop">
				<text class="btn-text">取消</text>
			</view>
			<text class="header-title">裁剪图片</text>
			<view class="header-btn primary" @tap="confirmCrop">
				<text class="btn-text">确定</text>
			</view>
		</view>

		<!-- 裁剪区域 -->
		<view class="crop-content">
			<view class="image-container" :style="{ width: containerWidth + 'px', height: containerHeight + 'px' }">
				<!-- 原始图片 -->
				<image :src="originalImage" class="crop-image" mode="aspectFit" :style="imageStyle" @load="onImageLoad"
					@touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" />

				<!-- 裁剪框 -->
				<view class="crop-box" :style="cropBoxStyle">
					<!-- 四个角的控制点 -->
					<view class="control-point top-left" @touchstart="onControlStart($event, 'top-left')"
						@touchmove="onControlMove" @touchend="onControlEnd"></view>
					<view class="control-point top-right" @touchstart="onControlStart($event, 'top-right')"
						@touchmove="onControlMove" @touchend="onControlEnd"></view>
					<view class="control-point bottom-left" @touchstart="onControlStart($event, 'bottom-left')"
						@touchmove="onControlMove" @touchend="onControlEnd"></view>
					<view class="control-point bottom-right" @touchstart="onControlStart($event, 'bottom-right')"
						@touchmove="onControlMove" @touchend="onControlEnd"></view>

					<!-- 裁剪框边框 -->
					<view class="crop-border"></view>
				</view>

				<!-- 遮罩层 -->
				<view class="crop-mask">
					<view class="mask-top" :style="{ height: cropBox.y + 'px' }"></view>
					<view class="mask-middle" :style="{ top: cropBox.y + 'px', height: cropBox.height + 'px' }">
						<view class="mask-left" :style="{ width: cropBox.x + 'px' }"></view>
						<view class="mask-right" :style="{ left: (cropBox.x + cropBox.width) + 'px' }"></view>
					</view>
					<view class="mask-bottom" :style="{ top: (cropBox.y + cropBox.height) + 'px' }"></view>
				</view>
			</view>
		</view>

		<!-- 底部工具栏 -->
		<view class="crop-toolbar">
			<view class="tool-item" @tap="resetCrop">
				<image src="/static/icons/reset.png" class="tool-icon" mode="aspectFit"></image>
				<text class="tool-text">重置</text>
			</view>

			<view class="tool-item" @tap="rotateCrop">
				<image src="/static/icons/rotate.png" class="tool-icon" mode="aspectFit"></image>
				<text class="tool-text">旋转</text>
			</view>

			<view class="tool-item" @tap="toggleAspectRatio">
				<image src="/static/icons/ratio.png" class="tool-icon" mode="aspectFit"></image>
				<text class="tool-text">{{ aspectRatioText }}</text>
			</view>
		</view>

		<!-- 加载中 -->
		<view v-if="isProcessing" class="loading-overlay">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">处理中...</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				originalImage: '',
				imageWidth: 0,
				imageHeight: 0,
				containerWidth: 0,
				containerHeight: 0,

				// 裁剪框数据
				cropBox: {
					x: 50,
					y: 50,
					width: 200,
					height: 200
				},

				// 图片变换数据
				imageTransform: {
					scale: 1,
					translateX: 0,
					translateY: 0,
					rotation: 0
				},

				// 触摸相关
				touchData: {
					startX: 0,
					startY: 0,
					startCropBox: null,
					activeControl: null,
					isDragging: false
				},

				// 宽高比选项
				aspectRatios: [{
						name: '自由',
						value: 0
					},
					{
						name: '1:1',
						value: 1
					},
					{
						name: '4:3',
						value: 4 / 3
					},
					{
						name: '16:9',
						value: 16 / 9
					},
					{
						name: '3:4',
						value: 3 / 4
					},
					{
						name: '9:16',
						value: 9 / 16
					}
				],
				currentAspectRatio: 0,

				isProcessing: false
			}
		},

		computed: {
			imageStyle() {
				const {
					scale,
					translateX,
					translateY,
					rotation
				} = this.imageTransform;
				return {
					transform: `scale(${scale}) translate(${translateX}px, ${translateY}px) rotate(${rotation}deg)`,
					width: this.imageWidth + 'px',
					height: this.imageHeight + 'px'
				};
			},

			cropBoxStyle() {
				return {
					left: this.cropBox.x + 'px',
					top: this.cropBox.y + 'px',
					width: this.cropBox.width + 'px',
					height: this.cropBox.height + 'px'
				};
			},

			aspectRatioText() {
				return this.aspectRatios[this.currentAspectRatio].name;
			}
		},

		onLoad(options) {
			this.originalImage = decodeURIComponent(options.imagePath);
			this.imageWidth = parseInt(options.width) || 300;
			this.imageHeight = parseInt(options.height) || 300;

			// 获取容器尺寸
			this.getContainerSize();

			// 初始化裁剪框
			this.initCropBox();
		},

		methods: {
			// 获取容器尺寸
			getContainerSize() {
				const systemInfo = uni.getSystemInfoSync();
				this.containerWidth = systemInfo.windowWidth;
				this.containerHeight = systemInfo.windowHeight - 200; // 减去头部和底部工具栏高度
			},

			// 初始化裁剪框
			initCropBox() {
				const size = Math.min(this.containerWidth, this.containerHeight) * 0.6;
				this.cropBox = {
					x: (this.containerWidth - size) / 2,
					y: (this.containerHeight - size) / 2,
					width: size,
					height: size
				};
			},

			// 图片加载完成
			onImageLoad(e) {
				console.log('图片加载完成', e);
			},

			// 触摸开始
			onTouchStart(e) {
				const touch = e.touches[0];
				this.touchData.startX = touch.clientX;
				this.touchData.startY = touch.clientY;
				this.touchData.isDragging = true;
			},

			// 触摸移动
			onTouchMove(e) {
				if (!this.touchData.isDragging) return;

				e.preventDefault();
				const touch = e.touches[0];
				const deltaX = touch.clientX - this.touchData.startX;
				const deltaY = touch.clientY - this.touchData.startY;

				// 移动图片
				this.imageTransform.translateX += deltaX * 0.5;
				this.imageTransform.translateY += deltaY * 0.5;

				this.touchData.startX = touch.clientX;
				this.touchData.startY = touch.clientY;
			},

			// 触摸结束
			onTouchEnd() {
				this.touchData.isDragging = false;
			},

			// 控制点触摸开始
			onControlStart(e, position) {
				e.stopPropagation();
				const touch = e.touches[0];
				this.touchData.startX = touch.clientX;
				this.touchData.startY = touch.clientY;
				this.touchData.activeControl = position;
				this.touchData.startCropBox = {
					...this.cropBox
				};
			},

			// 控制点移动
			onControlMove(e) {
				if (!this.touchData.activeControl) return;

				e.preventDefault();
				e.stopPropagation();

				const touch = e.touches[0];
				const deltaX = touch.clientX - this.touchData.startX;
				const deltaY = touch.clientY - this.touchData.startY;

				this.updateCropBox(deltaX, deltaY);
			},

			// 控制点触摸结束
			onControlEnd() {
				this.touchData.activeControl = null;
				this.touchData.startCropBox = null;
			},

			// 更新裁剪框
			updateCropBox(deltaX, deltaY) {
				const {
					activeControl,
					startCropBox
				} = this.touchData;
				const aspectRatio = this.aspectRatios[this.currentAspectRatio].value;

				let newCropBox = {
					...startCropBox
				};

				switch (activeControl) {
					case 'top-left':
						newCropBox.x += deltaX;
						newCropBox.y += deltaY;
						newCropBox.width -= deltaX;
						newCropBox.height -= deltaY;
						break;
					case 'top-right':
						newCropBox.y += deltaY;
						newCropBox.width += deltaX;
						newCropBox.height -= deltaY;
						break;
					case 'bottom-left':
						newCropBox.x += deltaX;
						newCropBox.width -= deltaX;
						newCropBox.height += deltaY;
						break;
					case 'bottom-right':
						newCropBox.width += deltaX;
						newCropBox.height += deltaY;
						break;
				}

				// 应用宽高比约束
				if (aspectRatio > 0) {
					if (newCropBox.width / newCropBox.height > aspectRatio) {
						newCropBox.width = newCropBox.height * aspectRatio;
					} else {
						newCropBox.height = newCropBox.width / aspectRatio;
					}
				}

				// 边界检查
				newCropBox.x = Math.max(0, Math.min(newCropBox.x, this.containerWidth - newCropBox.width));
				newCropBox.y = Math.max(0, Math.min(newCropBox.y, this.containerHeight - newCropBox.height));
				newCropBox.width = Math.max(50, Math.min(newCropBox.width, this.containerWidth - newCropBox.x));
				newCropBox.height = Math.max(50, Math.min(newCropBox.height, this.containerHeight - newCropBox.y));

				this.cropBox = newCropBox;
			},

			// 重置裁剪
			resetCrop() {
				this.imageTransform = {
					scale: 1,
					translateX: 0,
					translateY: 0,
					rotation: 0
				};
				this.initCropBox();
			},

			// 旋转图片
			rotateCrop() {
				this.imageTransform.rotation += 90;
				if (this.imageTransform.rotation >= 360) {
					this.imageTransform.rotation = 0;
				}
			},

			// 切换宽高比
			toggleAspectRatio() {
				this.currentAspectRatio = (this.currentAspectRatio + 1) % this.aspectRatios.length;

				// 应用新的宽高比
				const aspectRatio = this.aspectRatios[this.currentAspectRatio].value;
				if (aspectRatio > 0) {
					if (this.cropBox.width / this.cropBox.height > aspectRatio) {
						this.cropBox.width = this.cropBox.height * aspectRatio;
					} else {
						this.cropBox.height = this.cropBox.width / aspectRatio;
					}
				}
			},

			// 取消裁剪
			cancelCrop() {
				uni.navigateBack();
			},

			// 确认裁剪
			confirmCrop() {
				this.isProcessing = true;

				// 模拟裁剪处理
				setTimeout(() => {
					// 这里应该调用实际的图片裁剪API
					const croppedPath = this.processCropImage();

					this.isProcessing = false;

					// 返回裁剪结果
					const eventChannel = this.getOpenerEventChannel();
					eventChannel.emit('cropComplete', {
						croppedPath: croppedPath,
						cropData: {
							x: this.cropBox.x,
							y: this.cropBox.y,
							width: this.cropBox.width,
							height: this.cropBox.height,
							transform: this.imageTransform
						}
					});

					uni.navigateBack();
				}, 2000);
			},

			// 处理图片裁剪（模拟）
			processCropImage() {
				// 在实际应用中，这里应该调用canvas API进行图片裁剪
				// 或者调用原生插件进行处理

				// 返回处理后的图片路径（这里返回原图作为示例）
				return this.originalImage;
			},
			getOpenerEventChannel() {
				return uni.getOpenerEventChannel();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.crop-container {
		width: 100vw;
		height: 100vh;
		background-color: #000;
		display: flex;
		flex-direction: column;
	}

	.crop-header {
		height: 88rpx;
		background-color: rgba(0, 0, 0, 0.8);
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
	}

	.header-btn {
		padding: 10rpx 20rpx;
		border-radius: 8rpx;

		&.primary {
			background-color: #007bff;
		}
	}

	.btn-text {
		color: white;
		font-size: 28rpx;
	}

	.header-title {
		color: white;
		font-size: 32rpx;
		font-weight: 500;
	}

	.crop-content {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.image-container {
		position: relative;
		overflow: hidden;
	}

	.crop-image {
		position: absolute;
		top: 50%;
		left: 50%;
		transform-origin: center;
		margin-left: -50%;
		margin-top: -50%;
	}

	.crop-box {
		position: absolute;
		border: 2rpx solid #fff;
		box-shadow: 0 0 0 9999rpx rgba(0, 0, 0, 0.5);
	}

	.control-point {
		position: absolute;
		width: 20rpx;
		height: 20rpx;
		background-color: #fff;
		border: 2rpx solid #007bff;
		border-radius: 50%;

		&.top-left {
			top: -10rpx;
			left: -10rpx;
		}

		&.top-right {
			top: -10rpx;
			right: -10rpx;
		}

		&.bottom-left {
			bottom: -10rpx;
			left: -10rpx;
		}

		&.bottom-right {
			bottom: -10rpx;
			right: -10rpx;
		}
	}

	.crop-border {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		pointer-events: none;
	}

	.crop-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		pointer-events: none;
	}

	.mask-top,
	.mask-bottom {
		position: absolute;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.mask-bottom {
		bottom: 0;
	}

	.mask-middle {
		position: absolute;
		left: 0;
		right: 0;
		display: flex;
	}

	.mask-left,
	.mask-right {
		background-color: rgba(0, 0, 0, 0.5);
		height: 100%;
	}

	.mask-right {
		position: absolute;
		right: 0;
	}

	.crop-toolbar {
		height: 120rpx;
		background-color: rgba(0, 0, 0, 0.8);
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding: 0 30rpx;
	}

	.tool-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10rpx;
	}

	.tool-icon {
		width: 40rpx;
		height: 40rpx;
		margin-bottom: 8rpx;
	}

	.tool-text {
		color: white;
		font-size: 24rpx;
	}

	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.loading-content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.3);
		border-top: 4rpx solid #fff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		color: white;
		font-size: 28rpx;
	}
</style>